package com.bdqn.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.bdqn.springboot.dao.BookDao;
import com.bdqn.springboot.entity.Book;
import com.bdqn.springboot.service.BookService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Book)表服务实现类
 *
 * @author makejava
 * @since 2023-09-07 09:36:05
 */
@Service("bookService")
public class BookServiceImpl implements BookService {
    @Resource
    private BookDao bookDao;

    @Resource
    StringRedisTemplate stringRedisTemplate;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Book queryById(Integer id) {
        return this.bookDao.queryById(id);
    }



    /**
     * 新增数据
     *
     * @param book 实例对象
     * @return 实例对象
     */
    @Override
    public Book insert(Book book) {
        this.bookDao.insert(book);
        return book;
    }

    /**
     * 修改数据
     *
     * @param book 实例对象
     * @return 实例对象
     */
    @Override
    public Book update(Book book) {
        this.bookDao.update(book);
        return this.queryById(book.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.bookDao.deleteById(id) > 0;
    }

    @Override
    public List<Book> getListAll(String bookname) {
        //先判断redis是否存有图书信息
        if (stringRedisTemplate.hasKey("book")){
            String book = stringRedisTemplate.opsForValue().get("book");
            return JSON.parseArray(book, Book.class);
        }else{
            List<Book> listAll = bookDao.getListAll(bookname);
            stringRedisTemplate.opsForValue().set("book",JSON.toJSONString(listAll));
            return listAll;
        }
    }
}
